<template>
  <div class="budget-form">
    <!-- 课题预算填写卡片 -->
    <el-card
      v-for="topic in topics"
      :key="topic.topicName"
      class="topic-card"
    >
      <template #header>
        <span class="topic-title">课题预算填写: {{ topic.topicName }}</span>
      </template>

      <!-- 预算科目树形表格 -->
      <el-table
        :data="computedBudgetTree(topic.topicName)"
        row-key="subjectId"
        :indent="30"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        border
        default-expand-all
        size="small"
        class="budget-table"

      >
        <!-- 科目层级缩进显示 -->
        <el-table-column prop="subjectName" label="预算科目" min-width="220">
          <template #default="{ row }">
            <span :style="{
              marginLeft: `${(row.subjectLevel - 1) * 20}px`,
              fontWeight: row.subjectLevel === 1 ? 'bold' : 'normal'
            }">
              {{ row.subjectName }}
              <el-tag v-if="row.isSummary" size="mini" type="info" style="margin-left:8px">汇总项</el-tag>
            </span>
          </template>
        </el-table-column>

        <!-- 财政经费填写 -->
        <el-table-column label="财政经费(万元)" width="160">
          <template #default="{ row }">
            <el-input-number
              v-if="row.editable"
              v-model="formData[topic.topicName][row.subjectId].fiscalFunds"
              :min="0"
              :precision="2"
              :controls="false"
              size="small"
              style="width:100%"
              @change="calculateSummary(topic.topicName, row)"
            />
            <span v-else>{{ formatNumber(row.computedFiscal) }}</span>
          </template>
        </el-table-column>

        <!-- 自筹经费填写 -->
        <el-table-column label="自筹经费(万元)" width="160">
          <template #default="{ row }">
            <el-input-number
              v-if="row.editable"
              v-model="formData[topic.topicName][row.subjectId].selfFunds"
              :min="0"
              :precision="2"
              :controls="false"
              size="small"
              style="width:100%"
              @change="calculateSummary(topic.topicName, row)"
            />
            <span v-else>{{ formatNumber(row.computedSelf) }}</span>
          </template>
        </el-table-column>

        <!-- 合计金额 -->
        <el-table-column label="合计(万元)" width="120">
          <template #default="{ row }">
            <span v-if="row.editable">
              {{ formatNumber(
                formData[topic.topicName][row.subjectId].fiscalFunds +
                formData[topic.topicName][row.subjectId].selfFunds
              ) }}
            </span>
            <span v-else>{{ formatNumber(row.computedFiscal + row.computedSelf) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { getTemplate } from "@/api/sci/budgetTemplate";

export default {
  name: "BudgetForm",
  props: {
    projectId: {
      type: [String, Number], // 根据实际类型选择
      default: null
    },
    topics: {
      type: Array,
      required: true,
      default: () => []
    },
    templateId: {
      type: [Number, String],
      required: true
    },
    existingBudgetData: {
      type: Array,
      default: () => []
    }
  },
  // 添加 inject 选项
  inject: ['budgetDataManager'],
  data() {
    return {
      templateData: null,
      formData: {},
      calculatedSubjects: new Set()
    };
  },
  watch: {
     templateId: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          const numericId = typeof newVal === 'string' ? parseInt(newVal) : newVal;
          this.loadTemplateData(numericId).then(() => {
            // 模板数据加载完成后，如果有现有数据则设置
            if (this.existingBudgetData && this.existingBudgetData.length > 0) {
              this.$nextTick(() => {
                this.setExistingBudgetData(this.existingBudgetData);
              });
            }
          });
        }
      }
    },
    // 监听 topics 变化
    topics: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          // 当 topics 有数据时，重新初始化表单数据
          if (this.templateData) {
            this.initializeFormData();
            // 如果已有预算数据，也一并设置
            if (this.existingBudgetData && this.existingBudgetData.length > 0) {
              this.$nextTick(() => {
                this.setExistingBudgetData(this.existingBudgetData);
              });
            }
          }
        }
      },
      immediate: true
    },
    // 监听 formData 变化，当数据变化时通知父组件
    formData: {
      handler(newVal) {
        // 使用 nextTick 确保 DOM 更新完成后再生成数据
        this.$nextTick(() => {
          const data = this.generateSubmitData();
          // 通过 inject 的方法将数据传递给最上层组件
          if (this.budgetDataManager && this.budgetDataManager.updateBudgetData) {
            this.budgetDataManager.updateBudgetData(data);
          }
        });
      },
      deep: true // 深度监听
    },
    existingBudgetData: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          // 确保模板数据已加载
          if (this.templateData) {
            this.$nextTick(() => {
              this.setExistingBudgetData(newVal);
            });
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    formatNumber(value) {
      return (parseFloat(value) || 0).toFixed(2);
    },

    async loadTemplateData(templateId) {
      try {
        const res = await getTemplate(templateId);
        this.templateData = res.data;
        this.initializeFormData();
        return Promise.resolve(); // 确保返回 Promise
      } catch (error) {
        console.error("加载预算模板失败:", error);
        this.$message.error("预算模板加载失败，请重试");
        return Promise.reject(error); // 确保返回 Promise
      }
    },

    initializeFormData() {
      this.calculatedSubjects.clear();
      this.formData = {};

      // 添加空值保护
      if (!this.templateData || !this.templateData.sciBudgetSubjectList) {
        return;
      }

      this.topics.forEach(topic => {
        const topicName = topic.topicName;
        this.$set(this.formData, topicName, {});

        const traverse = (nodes) => {
          nodes.forEach(node => {
            if (node.editable) {
              this.$set(this.formData[topicName], node.subjectId, {
                fiscalFunds: 0,
                selfFunds: 0
              });
            }
            if (node.children) traverse(node.children);
          });
        };

        const tree = this.buildSubjectTree();
        if (tree && tree.length > 0) {
          traverse(tree);
        }
      });
    },

    buildSubjectTree() {
      if (!this.templateData || !this.templateData.sciBudgetSubjectList) {
        return [];
      }

      const list = [...this.templateData.sciBudgetSubjectList];
      const map = {};
      const roots = [];

      // 初始化节点结构
      list.forEach(item => {
        map[item.subjectId] = {
          ...item,
          computedFiscal: 0,
          computedSelf: 0,
          children: []
        };
      });

      // 构建树形结构
      list.forEach(item => {
        const parentId = item.parentId;
        if (parentId === "0" || !map[parentId]) {
          roots.push(map[item.subjectId]);
        } else {
          map[parentId].children.push(map[item.subjectId]);
        }
      });

      // 子节点排序
      const sortChildren = (node) => {
        if (node.children && node.children.length) {
          node.children.sort((a, b) => a.sortOrder - b.sortOrder);
          node.children.forEach(sortChildren);
        }
      };

      roots.forEach(sortChildren);
      return roots.sort((a, b) => a.sortOrder - b.sortOrder);
    },

    computedBudgetTree(topicName) {
      // 添加空值保护
      if (!this.templateData || !this.templateData.sciBudgetSubjectList) {
        return [];
      }

      const tree = this.buildSubjectTree().map(node => this.deepClone(node));

      const computeNode = (node) => {
        if (node.editable) {
          const funds = this.formData[topicName]?.[node.subjectId] || { fiscalFunds: 0, selfFunds: 0 };
          node.computedFiscal = parseFloat(funds.fiscalFunds) || 0;
          node.computedSelf = parseFloat(funds.selfFunds) || 0;
          return { fiscalFunds: node.computedFiscal, selfFunds: node.computedSelf };
        }

        let fiscalSum = 0;
        let selfSum = 0;

        if (node.children && node.children.length) {
          node.children.forEach(child => {
            const childFunds = computeNode(child);
            fiscalSum += childFunds.fiscalFunds;
            selfSum += childFunds.selfFunds;
          });
        }

        node.computedFiscal = fiscalSum;
        node.computedSelf = selfSum;
        return { fiscalFunds: fiscalSum, selfFunds: selfSum };
      };

      // 计算整个树的值
      tree.forEach(root => computeNode(root));
      return tree;
    },

    // 深度克隆方法
    deepClone(obj) {
      if (typeof obj !== 'object' || obj === null) return obj;
      const copy = Array.isArray(obj) ? [] : {};
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          copy[key] = this.deepClone(obj[key]);
        }
      }
      return copy;
    },

    calculateSummary(topicName, row) {
      const markForRecalculation = (nodeId) => {
        if (!nodeId || nodeId === "0") return;
        this.calculatedSubjects.add(nodeId);

        const findNode = (nodes) => {
          for (const node of nodes) {
            if (node.subjectId === nodeId && node.parentId && node.parentId !== "0") {
              markForRecalculation(node.parentId);
              break;
            }
            if (node.children && node.children.length) {
              findNode(node.children);
            }
          }
        };

        const tree = this.buildSubjectTree();
        if (tree && tree.length > 0) {
          findNode(tree);
        }
      };

      markForRecalculation(row.subjectId);
      this.$forceUpdate();
    },



    // generateSubmitData() {
    //   const result = [];
    //   const budgetTemplateId = typeof this.templateId === 'string' ? parseInt(this.templateId) : this.templateId;

    //   Object.keys(this.formData).forEach(topicName => {
    //     const topic = this.topics.find(t => t.topicName === topicName);

    //     Object.keys(this.formData[topicName]).forEach(subjectId => {
    //       const funds = this.formData[topicName][subjectId];
    //       result.push({
    //         projectId: this.projectId,
    //         budgetTemplateId,
    //         subjectId: parseInt(subjectId),
    //         topicName,
    //         fiscalFunds: parseFloat(funds.fiscalFunds) || 0,
    //         selfFunds: parseFloat(funds.selfFunds) || 0
    //       });
    //     });
    //   });

    //   return result;
    // },

    generateSubmitData() {
      const result = [];
      const budgetTemplateId = typeof this.templateId === 'string' ? parseInt(this.templateId) : this.templateId;

      // 遍历所有课题
      Object.keys(this.formData).forEach(topicName => {
        // 获取该课题的完整预算树（包含可编辑和不可编辑的行）
        const budgetTree = this.computedBudgetTree(topicName);

        // 递归遍历树形结构，收集所有节点数据
        const traverseTree = (nodes) => {
          nodes.forEach(node => {
            // 添加当前节点数据
            result.push({
              projectId:this.projectId || 0,
              budgetTemplateId,
              subjectId: parseInt(node.subjectId),
              topicName,
              fiscalFunds: parseFloat(node.computedFiscal) || 0,
              selfFunds: parseFloat(node.computedSelf) || 0,
              editable: !!node.editable, // 标记是否为可编辑行
              subjectName: node.subjectName, // 添加科目名称便于识别
              subjectLevel: node.subjectLevel // 添加科目层级
            });

            // 递归处理子节点
            if (node.children && node.children.length) {
              traverseTree(node.children);
            }
          });
        };

        traverseTree(budgetTree);
      });

      return result;
    },

    resetForm() {
      Object.keys(this.formData).forEach(topicName => {
        Object.keys(this.formData[topicName]).forEach(subjectId => {
          this.formData[topicName][subjectId].fiscalFunds = 0;
          this.formData[topicName][subjectId].selfFunds = 0;
        });
      });
      this.$forceUpdate();
    },
    setExistingBudgetData(budgetData) {
       if (!budgetData || budgetData.length === 0) return;

      // 按课题名称分组数据
      const groupedData = {};
      budgetData.forEach(item => {
        if (!groupedData[item.topicName]) {
          groupedData[item.topicName] = {};
        }
        groupedData[item.topicName][item.subjectId] = {
          fiscalFunds: parseFloat(item.fiscalFunds) || 0,
          selfFunds: parseFloat(item.selfFunds) || 0
        };
      });

      // 确保formData已初始化
      if (!this.formData || Object.keys(this.formData).length === 0) {
        this.initializeFormData();
      }

      // 更新formData
      Object.keys(groupedData).forEach(topicName => {
        // 确保课题名称在formData中存在
        if (!this.formData[topicName]) {
          this.$set(this.formData, topicName, {});
        }

        // 为每个科目设置数据
        Object.keys(groupedData[topicName]).forEach(subjectId => {
          this.$set(this.formData[topicName], subjectId, groupedData[topicName][subjectId]);
        });
      });

      this.$forceUpdate();
    }
  }
};
</script>

<style scoped>
.budget-form {
  padding: 10px 0;
}

.topic-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.topic-title {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.budget-table {
  width: 100%;
  margin-top: 10px;
  font-size: 14px;
}

.el-table .el-table__row td {
  padding: 4px 0;
}

.budget-table .el-input-number {
  width: 100%;
}

.budget-table .el-input-number ::v-deep .el-input__inner {
  text-align: left;
  padding: 0 8px;
}
</style>
